const dayjs = require('dayjs'); // 时间处理库
const relativeTime = require('dayjs/plugin/relativeTime');
dayjs.extend(relativeTime);
const updateLocale = require('dayjs/plugin/updateLocale')

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const fromNowFormat = value => {
  require('dayjs/locale/zh-cn');
  dayjs.locale('zh-cn');
  return value ? dayjs(value).fromNow() : "";
}
const formatTimeCommon = value => {
  return value ? dayjs(value).format('YYYY-MM-DD') : "";
}
const calculateAge = value => {
  let age = dayjs(value).fromNow();
  age = parseInt(age, 10) || '未知';
  return age;
}
const calculateConstellation = value => {
  const month = dayjs(value).month() + 1;
  const date = dayjs(value).date();
  const constellations = "魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
  const nums = [20,19,21,21,21,22,23,23,23,23,22,22];
  const result = constellations.substr(month * 2 - (date < nums[month-1] ? 2 : 0), 2);
  return result;

}

function getDateDiff(dateTimeStamp) {
  var result;
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();
  var diffValue = now - dateTimeStamp;
  if (diffValue < 0) {
    return;
  }
  var monthC = diffValue / month;
  var weekC = diffValue / (7 * day);
  var dayC = diffValue / day;
  var hourC = diffValue / hour;
  var minC = diffValue / minute;
  if (monthC >= 1) {
    if (monthC <= 12)
      result = "" + parseInt(monthC) + "月前";
    else {
      result = "" + parseInt(monthC / 12) + "年前";
    }
  }
  else if (weekC >= 1) {
    result = "" + parseInt(weekC) + "周前";
  }
  else if (dayC >= 1) {
    result = "" + parseInt(dayC) + "天前";
  }
  else if (hourC >= 1) {
    result = "" + parseInt(hourC) + "小时前";
  }
  else if (minC >= 1) {
    result = "" + parseInt(minC) + "分钟前";
  } else {
    result = "刚刚";
  }
  return result;
};

module.exports = {
  formatTime: formatTime,
  fromNowFormat: fromNowFormat,
  formatTimeCommon: formatTimeCommon,
  calculateAge: calculateAge,
  calculateConstellation: calculateConstellation,
  getDateDiff: getDateDiff
}
